<!-- 搜索表单 -->
<template>
  <a-card :bordered="false">
    <!-- 表格 -->
    <ele-pro-table ref="applyCustomsFeeTableRef" row-key="id" :columns="columns" :datasource="datasource" :scroll="{ x: 1000 }"
      :needPage="false">
      <template #toolbar>
        <a-space>
          <a-button v-if="applyCustomsId > 0" type="primary" @click="applyCustomsFeeOpenEdit(null, 'receivable')"
            v-any-permission="['order:applyCustomsFee:save']">
            <template #icon>
              <plus-outlined />
            </template>
            <span>应收</span>
          </a-button>
        </a-space>
        <a-space class="space">
          <a-button v-if="applyCustomsId > 0" class="re" @click="applyCustomsFeeOpenEdit(null, 'payable')"
            v-any-permission="['order:applyCustomsFee:save']">
            <template #icon>
              <plus-outlined />
            </template>
            <span>应付</span>
          </a-button>
        </a-space>
        应收 {{ fee.receivable }} 应付 {{ fee.payable }} 利润 {{ fee.total }}
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'type'">
          <a-tag v-if="record.type=='应收'" color="blue">
            {{ record.type }}
          </a-tag>
          <a-tag v-if="record.type=='应付'" color="red">
            {{ record.type }}
          </a-tag>
        </template>
        <template v-if="column.key === 'action'">
          <a-space>
            <a @click="applyCustomsFeeOpenEdit(record)" v-any-permission="['order:applyCustomsFee:update']">修改</a>
            <a-divider type="vertical" />
            <a-popconfirm title="确定要删除此项吗？" @confirm="applyCustomsFeeRemove(record)">
              <a class="ele-text-danger" v-any-permission="['order:applyCustomsFee:remove']">删除</a>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </ele-pro-table>
  </a-card>
  <!-- 海运运费添加、修改弹窗 -->
  <ele-modal :width="560" v-model:visible="applyCustomsFeeVisible_modal" :confirm-loading="loading"
    :title="applyCustomsFeeIsUpdate ? '修改' + payable_receivable_type + '海运运费' : '' + payable_receivable_type + '海运运费'"
    :body-style="{ paddingBottom: '8px' }" @ok="applyCustomsFeeSave" :maskClosable="false">
    <a-form ref="applyCustomsFeeFormRef" :model="applyCustomsFeeForm" :rules="applyCustomsFeeRules"
      :label-col="{ md: { span: 7 }, sm: { span: 24 } }" :wrapper-col="{ md: { span: 17 }, sm: { span: 24 } }">
      <a-form-item label="费用方向" name="type">
        <a-input allow-clear :maxlength="200" placeholder="费用方向" v-model:value="applyCustomsFeeForm.type" autocomplete="off"
          disabled="true" />
      </a-form-item>
      <a-form-item label="费用名称" name="feeName">
        <a-auto-complete v-model:value="applyCustomsFeeForm.feeName_val" :options="feeNameOptions" placeholder="请输入"
          @select="feeName_onSelect" @search="feeName_onSearch" @blur="feeName_blur" allow-clear />
      </a-form-item>
      <a-form-item label="金额" name="price">
        <a-input allow-clear :maxlength="200" placeholder="请输入金额" v-model:value="applyCustomsFeeForm.price" autocomplete="off" />
      </a-form-item>
      <a-form-item label="模块" name="feeModules">
        <a-input allow-clear :maxlength="200" placeholder="请输入模块" v-model:value="applyCustomsFeeForm.feeModules"
          autocomplete="off" disabled="true"/>
      </a-form-item>
      <a-form-item label="抬头" name="invoicename">
          <a-auto-complete v-model:value="applyCustomsFeeForm.invoicename_val" :options="invoicenameOptions" placeholder="请输入"
          @select="invoicename_onSelect" @search="invoicename_onSearch" @blur="invoicename_blur" allow-clear />
      </a-form-item>
      <a-form-item label="开票" name="invoicestate">
          <a-select v-model:value="applyCustomsFeeForm.invoicestate" placeholder="请选择" allow-clear>
          <a-select-option value="1">开票</a-select-option>
          <a-select-option value="0">不开票</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="币种" name="currency">
          <a-select v-model:value="applyCustomsFeeForm.currency" placeholder="请选择" allow-clear>
          <a-select-option value="CNY">CNY</a-select-option>
          <a-select-option value="USD">USD</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="汇率" name="exchangeRate">
        <a-input allow-clear :maxlength="200" placeholder="请输入汇率" v-model:value="applyCustomsFeeForm.exchangeRate"
          autocomplete="off" />
      </a-form-item>
      <a-form-item label="备注" name="remark">
        <a-input allow-clear :maxlength="200" placeholder="请输入备注" v-model:value="applyCustomsFeeForm.remark"
          autocomplete="off" />
      </a-form-item>
    </a-form>
  </ele-modal>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { toDateString } from 'ele-admin-pro';
import useFormData from '@/utils/use-form-data';
import { message } from 'ant-design-vue';
import { TIME_OUT } from '@/config/damon';

import { listMaintainFeeAttachsSel } from '@/api/order/maintainFeeAttach';
import { listInvoiceSel } from '@/api/order/customer';
import { pageApplyCustomsFee, removeApplyCustomsFee, addApplyCustomsFee, updateApplyCustomsFee } from '@/api/order/applyCustomsFee';



// 表格实例
const applyCustomsFeeTableRef = ref(null);

// 表格列配置
const columns = ref([
  {
    key: 'index',
    width: 48,
    align: 'center',
    fixed: 'left',
    hideInSetting: true,
    customRender: ({ index }) => index + (applyCustomsFeeTableRef.value?.tableIndex ?? 0)
  },
  {
    title: '类型',
    dataIndex: 'type',
    key: 'type',
    // sorter: true
  },
  {
    title: '费用名称',
    dataIndex: 'feeName',
    key: 'feeName',
    // sorter: true
  },
  {
    title: '金额',
    dataIndex: 'price',
    key: 'price',
    // sorter: true
  },
  {
    title: '模块',
    dataIndex: 'feeModules',
    key: 'feeModules',
    // sorter: true
  },
  {
    title: '抬头',
    dataIndex: 'invoicename',
    key: 'invoicename',
    // sorter: true
  },
  {
    title: '开票',
    dataIndex: 'invoicestate',
    key: 'invoicestate',
    // sorter: true
  },
  {
    title: '币种',
    dataIndex: 'currency',
    key: 'currency',
    // sorter: true
  },
  {
    title: '汇率',
    dataIndex: 'exchangeRate',
    key: 'exchangeRate',
    // sorter: true
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
    // sorter: true
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    resizable: true,
    width: 150,
    ellipsis: true,
    customRender: ({ text }) => toDateString(text)
  },
  {
    title: '创建人',
    dataIndex: 'createName',
    key: 'createName',
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    key: 'updateTime',
    resizable: true,
    width: 150,
    ellipsis: true,
    customRender: ({ text }) => toDateString(text)
  },
  {
    title: '更新人',
    dataIndex: 'updateName',
    key: 'updateName',
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    align: 'center',
    fixed: 'right',
    hideInSetting: true
  }
]);

// 表单数据
const { form: applyCustomsFeeWhere, resetFields } = useFormData({
  username: '',
  sex: undefined
});

let applyCustomsId = ref(0)
let applyCustoms = reactive(null)
// 表格数据源
let fee = reactive({
  'payable': 0,
  'receivable': 0,
  'total': 0,
})
const datasource = async ({ page, limit, where, orders }) => {
  if (applyCustomsId.value == 0) {
    return new Promise((resolve) => {
      resolve({ count: 0, list: [] })
    })
  }
  limit = 1000
  fee.payable = 0
  fee.receivable = 0
  fee.total = 0
  let data_temp = {}
  await pageApplyCustomsFee({ ...where, ...orders, page, limit }).then((msg) => {
    data_temp = msg
    msg.list.forEach(element => {
      if (element.type == '应收') {
        fee.receivable += parseFloat(element.price) * parseFloat(element.exchangeRate)
      } else if (element.type = '应付') {
        fee.payable += parseFloat(element.price) * parseFloat(element.exchangeRate)
      }
      fee.total = fee.receivable - fee.payable
    });
  }).catch((e) => {
  });
  return new Promise((resolve) => {
    resolve(data_temp)
  })


};

/* 搜索 */
// {
  // 'applyCustomsId': applyCustomsCurrent.value.id,
  //   'invoice': {
  //     'company': applyCustomsCurrent.value.customer,
  //     'applyCustoms': applyCustomsCurrent.value.applyCustoms,
  //   }
//   }
const applyCustomsFeeReload = (applyCustoms2) => {
  applyCustomsId.value = applyCustoms2.applyCustomsId
  applyCustoms = applyCustoms2
  applyCustomsFeeWhere.applyId = applyCustomsId.value
  applyCustomsFeeTableRef?.value?.reload({ page: 1, where: applyCustomsFeeWhere });
};

defineExpose({ applyCustomsFeeReload })

/*  重置 */
const applyCustomsFeeReset = () => {
  resetFields();
  applyCustomsFeeReload(applyCustoms);
};

/* 删除单个 */
const applyCustomsFeeRemove = (record) => {
  const hide = message.loading('请求中..', 0);
  removeApplyCustomsFee(record.id).then((msg) => {
    hide();
    message.success(msg);
    applyCustomsFeeReload(applyCustoms);
  }).catch((e) => {
    hide();
    message.error(e.message);
  });
};

// 当前选中数据
const applyCustomsFeeCurrent = ref(null);

// 弹窗是否打开
const applyCustomsFeeVisible_modal = ref(false);

// 是否是修改
const applyCustomsFeeIsUpdate = ref(false);

// 提交状态
const loading = ref(false);

//
const applyCustomsFeeFormRef = ref(null);

// 表单数据
const { form: applyCustomsFeeForm, resetFields: applyCustomsFeeResetFormFields } = useFormData({
  id: undefined,
  customer: '',
  vessel: '',
});

// 表单验证规则
const applyCustomsFeeRules = reactive({
  name: [
    {
      required: true,
      message: '请输入名称',
      type: 'string',
    }
  ],
});

//新建海运费用 默认显示抬头  防止重复刷新
let timeout = 0
const feeNameOptions = ref([]);
const feeName_onSearch = searchText => {
  clearTimeout(timeout)
  timeout = setTimeout(() => {
    listMaintainFeeAttachsSel({ 'name': searchText }).then(msg => {
      msg.map((element) => {
        element.label = element.label + ' -' + element.module
        element.value = element.value + '-' + element.price
      })
      feeNameOptions.value = msg
    }).catch((e) => {
    })
  }, TIME_OUT);
};
const feeName_onSelect = (value2, option2) => {
  // let a = feeNameOptions.value.find((item)=> {return item.value=value})
  // console.log(a.value,a.label)
  // form.name=a.value
  let label = option2.label.split(' -')[0]
  applyCustomsFeeForm.feeName_val = label
  applyCustomsFeeForm.feeName = label
  applyCustomsFeeForm.feeModules = option2.module
  applyCustomsFeeForm.price = option2.price
};
const feeName_change = (value2) => {
  let a = feeNameOptions.value.find((item) => { return item.value = value2 })
  applyCustomsFeeForm.feeName_val = a.label
  applyCustomsFeeForm.feeName = a.label
};
const feeName_blur = () => {
  applyCustomsFeeForm.feeName_val = applyCustomsFeeForm.feeName
};



//开票   防止重复刷新
const invoicenameOptions = ref([]);
const invoicename_onSearch = searchText => {
  clearTimeout(timeout)
  timeout = setTimeout(() => {
    listInvoiceSel({ 'name': searchText }).then(msg => {
      invoicenameOptions.value = msg
    }).catch((e) => {
    })
  }, TIME_OUT);
};
const invoicename_onSelect = (value2, option2) => {
  // let a = invoicenameOptions.value.find((item)=> {return item.value=value})
  // console.log(a.value,a.label)
  // { "code": 0, "data": [{ "value": "825", "label": "厦航厦航厦航厦航", "invoiceState": "0", "type": "" }], "message": "操作成功" }
  let label = option2.label.split(' -')[0]
  applyCustomsFeeForm.invoicename_val = label
  applyCustomsFeeForm.invoicename = label
  applyCustomsFeeForm.invoicestate = option2.invoiceState
};
const invoicename_blur = () => {
  // applyCustomsFeeForm.invoicename_val = applyCustomsFeeForm.invoicename
};
const invoicename_default_onSelect = async (b_type) => {
  await listInvoiceSel({ 'name': '' }).then(msg => {
    invoicenameOptions.value = msg
  }).catch((e) => {
  })
  let b_name = applyCustoms.invoice.company
  if (b_type == '应收') {
  } else if (b_type == '应付') {
    b_name = applyCustoms.invoice.customsAgent
  }
  if (b_name == null || b_name == undefined || b_name == '') { return }
  let option2 = invoicenameOptions.value.find((item) => {
    return item.label == b_name
  })
  applyCustomsFeeForm.invoicename_val = option2.label
  applyCustomsFeeForm.invoicename = option2.label
  applyCustomsFeeForm.invoicestate = option2.invoiceState
};

let payable_receivable_type = ref('')
/* 打开编辑弹窗 */
const applyCustomsFeeOpenEdit = (record, type_t) => {
  applyCustomsFeeResetFormFields();
  applyCustomsFeeFormRef.value?.clearValidate();
  applyCustomsFeeCurrent.value = record?? {};
  applyCustomsFeeVisible_modal.value = true;
  Object.assign(applyCustomsFeeForm, record ?? {});
  applyCustomsFeeIsUpdate.value = !!record;
  applyCustomsFeeForm.applyId = applyCustomsId.value
  if (type_t == 'receivable') {
    payable_receivable_type.value = '应收'
    applyCustomsFeeForm.type = '应收'
  }
  if (type_t == 'payable') {
    payable_receivable_type.value = '应付'
    applyCustomsFeeForm.type = '应付'
  }
  if (record == null) {
    invoicename_default_onSelect(payable_receivable_type.value)
    applyCustomsFeeForm.feeName_val = applyCustomsFeeForm.feeName
    applyCustomsFeeForm.currency="CNY"
    applyCustomsFeeForm.exchangeRate="1"
  } else {
    applyCustomsFeeForm.invoicename_val = applyCustomsFeeForm.invoicename
    applyCustomsFeeForm.feeName_val = applyCustomsFeeForm.feeName
  }
};

/* 保存编辑 */
const applyCustomsFeeSave = () => {
  if (!applyCustomsFeeFormRef.value) {
    return;
  }
  applyCustomsFeeFormRef.value.validate().then(() => {
    loading.value = true;
    const saveOrUpdate = applyCustomsFeeIsUpdate.value ? updateApplyCustomsFee : addApplyCustomsFee;
    saveOrUpdate(applyCustomsFeeForm).then((msg) => {
      loading.value = false;
      message.success(msg);
      applyCustomsFeeVisible_modal.value = false;
      applyCustomsFeeReload(applyCustoms);
    }).catch((e) => {
      loading.value = false;
      message.error(e.message);
    });
  }).catch(() => {
  });
};
</script>

<style lang="less" scoped>
@import "@/assets/css/public.less";

.re {
  background-color: @button-pay;
}

.space {
  margin-left: 10px;
  margin-right: 10px;
}
</style>
